//
//  LoginViewController.m
//  wanhucang
//
//  Created by 郝志宇 on 16/1/27.
//  Copyright © 2016年 XuDong Jin. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "FindPasswordViewController.h"
#import "WXApi.h"
#import <TencentOpenAPI/QQApiInterface.h>
#import "UMSocialQQHandler.h"
#import "IGLoginApi.h"
#import "AppDelegate.h"
#import "IGTLoginManager.h"
#import "userEditViewController.h"
#import "PhoneNumViewController.h"
#import "IGPwdTextField.h"
#import "IGGetMyinfoApi.h"
#import "IGNetReachable.h"
#import "IGMyCategoryView.h"

@interface LoginViewController () <UITableViewDataSource, UITableViewDelegate> {
    NSString *number;
    NSString *password;
}

@end

@implementation LoginViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
//    self.title = @"登录";
    self.title = NSLocalizedString(@"Login", nil);
    if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)]) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    
    self.table.backgroundColor = [UIColor whiteColor];
    [self setUI];
    
    number = [IGUser getTel];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDidTakeScreenshot) name:UIApplicationUserDidTakeScreenshotNotification object:nil];
}

-(void)setUI{
    UIImageView *iconview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, GSCALE(239))];
    iconview.backgroundColor =self.table.backgroundColor;
    iconview.image=[UIImage imageNamed:@"背景_首次登录"];
    
    __weak typeof(self) weakSelf = self;
    //登录头像
    UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, GSCALE(172), GSCALE(158))];
    img.image = [UIImage imageNamed:@"igallery_login"];
    img.contentMode = UIViewContentModeScaleAspectFit;
    img.center = iconview.center;
    [iconview addSubview:img];
    self.table.tableHeaderView=iconview;
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, GSCALE(150))];
    view.backgroundColor = self.table.backgroundColor;
    UIButton *login = [UIButton buttonWithType:UIButtonTypeCustom];
    login.layer.cornerRadius = 20.f;
    login.layer.masksToBounds = YES;
    login.backgroundColor = [UIColor appColor];
    login.frame = CGRectMake(0, 0, GSCALE(300), GSCALE(44));
    login.titleLabel.font = [UIFont font16];
    [login setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [login setTitle:@"登 录" forState:UIControlStateNormal];
    [login setTitle:NSLocalizedString(@"Login", nil) forState:UIControlStateNormal];
    [login addTarget:self action:@selector(loginAction:) forControlEvents:UIControlEventTouchUpInside];
    login.center = CGPointMake(view.width/2, login.height/2+30);
    [view addSubview:login];
    
    UILabel *registe = [[UILabel alloc] initWithFrame:CGRectMake(0, login.bottom+19 , GSCALE(100), GSCALE(23))];
    registe.left=login.left+14;
    registe.userInteractionEnabled = YES;
    registe.textAlignment = NSTextAlignmentLeft;
    registe.font = [UIFont font13];
//    registe.text = @"立即注册";
    registe.text = NSLocalizedString(@"Register Now", nil);
    registe.textColor = [UIColor c4Color];
    [view addSubview:registe];
    [registe setTapActionWithBlock:^{
        [weakSelf.view endEditing:YES];
        
        [UIViewController ig_pushViewControllerClass:[RegisterViewController class] animated:YES];
    }];
    
    UILabel *findPassword = [[UILabel alloc] initWithFrame:CGRectMake(0, login.bottom+19, GSCALE(120), GSCALE(23))];
    findPassword.right=login.right-14;
    findPassword.userInteractionEnabled = YES;
    findPassword.textAlignment = NSTextAlignmentRight;
    findPassword.font = [UIFont font13];
    findPassword.text = NSLocalizedString(@"Forget Password", nil);
    findPassword.textColor = [UIColor c4Color];
    [view addSubview:findPassword];
    [findPassword setTapActionWithBlock:^{
        [weakSelf.view endEditing:YES];
        
        [UIViewController ig_pushViewControllerClass:[FindPasswordViewController class] animated:YES];
    }];
    self.table.tableFooterView = view;
    
    CGFloat bottomGap = 80;
    if (iphoneX) {
        bottomGap = 120;
    }
    CGFloat itmeWidth = 45;
    CGRect rect = CGRectMake(0, KSCREENHEIGHT-itmeWidth-bottomGap, itmeWidth, itmeWidth);
    
    UIButton *wechat = [UIButton buttonWithType:UIButtonTypeCustom];
    wechat.frame = rect;
    wechat.tag = IGLoginTypeWChat;
    [wechat setImage:[UIImage imageNamed:@"login_weixin"] forState:UIControlStateNormal];
    [wechat addTarget:self action:@selector(otherLoginAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.table addSubview:wechat];
    
    UIButton *qq = [UIButton buttonWithType:UIButtonTypeCustom];
    qq.frame = rect;
    qq.tag = IGLoginTypeQQ;
    [qq setImage:[UIImage imageNamed:@"login_qq"] forState:UIControlStateNormal];
    [qq addTarget:self action:@selector(otherLoginAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.table addSubview:qq];
    
    UIButton *sina = [UIButton buttonWithType:UIButtonTypeCustom];
    sina.frame = rect;
    sina.tag = IGLoginTypeWeiBo;
    [sina setImage:[UIImage imageNamed:@"login_weibo"] forState:UIControlStateNormal];
    
    [sina addTarget:self action:@selector(otherLoginAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.table addSubview:sina];

    UILabel *sanfang = [[UILabel alloc] initWithFrame:CGRectMake(KSCREENWIDTH/2-GSCALE(200)/2, view.bottom, GSCALE(200), GSCALE(40))];
    sanfang.textColor = [UIColor c5Color];
    sanfang.font = [UIFont font12];
//    sanfang.text = @"第三方直接登录";
    sanfang.text = NSLocalizedString(@"Third-party Direct Login", nil);
    sanfang.textAlignment = NSTextAlignmentCenter;
    sanfang.bottom = qq.top - 10;
    [self.table addSubview:sanfang];
    
    CGFloat x3 = (KSCREENWIDTH - itmeWidth * 3) / 4;
    wechat.x = x3;
    qq.x = wechat.right + x3;
    sina.x = qq.right + x3;
}

#pragma mark - UITableViewDataSource, UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    CGFloat x = cell.separatorInset.left;
    UITextField *textView = [[UITextField alloc] initWithFrame:CGRectMake(x+21, 0, KSCREENWIDTH-2*36, 50)];
    textView.keyboardType = UIKeyboardTypePhonePad;
    if (indexPath.section==0) {
//        textView.placeholder = @"  手机号";
        textView.placeholder = NSLocalizedString(@"Mobile Number", nil);
        UIImageView *leftImageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 39, 24)];
        leftImageView.contentMode=UIViewContentModeLeft;
        leftImageView.image=[UIImage imageNamed:@"电话"];
        textView.leftView=leftImageView;
        textView.text = [IGUser getTel];
        [cell.contentView addSubview:textView];
        
        UILabel *line= [[UILabel alloc] initWithFrame:CGRectMake(textView.origin.x, 0, textView.width, 1)];
        line.top=cell.bottom;
        line.backgroundColor = [UIColor c6Color];
        [cell.contentView addSubview:line];
    }
    if (indexPath.section==1) {
        textView = [[IGPwdTextField alloc] initWithFrame:CGRectMake(x+21, 0, KSCREENWIDTH-2*36, 50)];
//        textView.placeholder = @"  密码";
        textView.placeholder = NSLocalizedString(@"Password", nil);

        UIImageView *ImageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 39, 24)];
        ImageView.contentMode=UIViewContentModeLeft;
        ImageView.image=[UIImage imageNamed:@"密码"];
        textView.leftView=ImageView;
        textView.text = password;
        textView.keyboardType = UIKeyboardTypeAlphabet;
        textView.secureTextEntry = YES;
        [cell.contentView addSubview:textView];
        
        UILabel *line= [[UILabel alloc] initWithFrame:CGRectMake(textView.x, 0, textView.width, 1)];
        line.top=cell.bottom;
        line.backgroundColor = [UIColor c6Color];
        [cell addSubview:line];
    }
    textView.borderStyle = UITextBorderStyleNone;
    textView.leftViewMode = UITextFieldViewModeAlways;
    textView.rightViewMode = UITextFieldViewModeUnlessEditing;
    textView.font = [UIFont font16];
    textView.textColor=[UIColor c4Color];
    textView.clearButtonMode = UITextFieldViewModeWhileEditing;
    [textView addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventEditingChanged];
    [textView addTarget:self action:@selector(textBeainEditing:) forControlEvents:UIControlEventEditingDidBegin];
    [textView addTarget:self action:@selector(textEndEditing:) forControlEvents:UIControlEventEditingDidEnd];
    textView.tag = indexPath.section;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==1) {
        return 0.01f;
    }else{
        return 0.01f;
    }
}

- (void)otherLoginAction:(UIButton *)btn {
    IGLoginType loginType = btn.tag;
    
    if (![IGNetReachable isReachable]) {
        [self presentMessageTips:NSLocalizedString(@"Network Connection Failed, Please Check Your Network Configuration.", nil)];
        return;
    }

    __weak typeof(self) weakSelf = self;
    IGTLoginManager *shareManager = [IGTLoginManager shareManager];
    [shareManager loginWithType:loginType vc:self block:^(id Resp) {
        if ([Resp isKindOfClass:[NSString class]]) {
            [weakSelf presentMessageTips:(NSString *)Resp];
        } else {
            [weakSelf customWithResp:Resp loginType:loginType];
        }
    }];
    
}

- (void)loginAction:(UIButton *)btn {
    [self.view endEditing:YES];
    if (![IGNetReachable isReachable]) {
        [self presentMessageTips:NSLocalizedString(@"Network Connection Failed, Please Check Your Network Configuration.", nil)];
        return;
    }
    if (number.length==0) {
//        [self presentMessageTips:@"请输入手机号"];
         [self presentMessageTips:NSLocalizedString(@"Please Input Mobile Number", nil)];
        return;
    }
    if (password.length==0) {
//        [self presentMessageTips:@"请输入密码"];
        [self presentMessageTips:NSLocalizedString(@"Please Input Password", nil)];
        return;
    }
    if (password.length<6) {
//        [self presentMessageTips:@"密码长度须6-16位"];
        [self presentMessageTips:NSLocalizedString(@"please input 6-16 digits or characters", nil)];
        return;
    }

    IGLoginApi *api = [[IGLoginApi alloc] initWithLoginType:IGLoginTypeNormal];
    api.username = number;
    api.password = password;
    __weak typeof(self) weakSelf = self;
    [api startWithDecodeClass:[IGLoginResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            [weakSelf customWithResp:responseObject loginType:IGLoginTypeNormal];
        }
    }];
}

- (void)customWithResp:(id)responseObject loginType:(IGLoginType)loginType {
    if (responseObject) {
//        [self presentMessageTips:@"登录成功"];
        [self presentMessageTips:NSLocalizedString(@"Login Successful", nil)];

        IGLoginResp *resp = responseObject;
        IGLoginModel *model = resp.data;
        IGUserInfo *userInfo = model.userinfo;
        
        [IGUser loginSuccessWithModel:userInfo completion:nil];
        
        [JPUSHService setAlias:userInfo.uid completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
        } seq:1];
        
        if (model.isFirst) {//第三方首次注册，引导绑定画屏
            if (loginType == IGLoginTypeNormal) {
                [UIViewController ig_pushViewControllerClass:[userEditViewController class] animated:YES];
            } else {
                PhoneNumViewController *phoneVC = [[UIStoryboard storyboardWithName:@"Setting" bundle:nil] instantiateViewControllerWithIdentifier:@"PhoneNumViewController"];
                phoneVC.thirdLoginFirst = YES;
                [UIViewController ig_pushViewController:phoneVC animated:YES];
            }
            return;
        }
        [self loadUserinfoData];
        if ([userInfo.hasLabelSetting integerValue]==0) {
            [IGMyCategoryView showIGMyCategoryView];
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
            [kAPPDELEGATE configTabBarVC];
            });
        
        }
    

        
    }
}

-(void)loadUserinfoData{
    IGGetMyinfoApi *meApi = [IGGetMyinfoApi new];
    [meApi startWithDecodeClass:[IGGetMyinfoResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            IGGetMyinfoResp *resp=responseObject;
            IGGetMyinfoModel *model=resp.data;
            IGUserInfo *userInfo = model.member;
            [IGUser saveUserInfo:userInfo];
        }
    }];
}

- (void)textBeainEditing:(UITextField *)textView {
    self.table.bounces = YES;
}

- (void)textEndEditing:(UITextField *)textView {
    self.table.bounces = NO;
}

- (void)textChange:(UITextField *)textView {
    if (textView.tag == 0) {
        //手机号
        if (textView.text.length>11) {
            textView.text = [textView.text substringToIndex:11];
        }
        number = textView.text;
    } else if (textView.tag == 1) {
        //密码
        if (textView.text.length>16) {
            textView.text = [textView.text substringToIndex:16];
        }
        password = textView.text;
    }
}

- (void)userDidTakeScreenshot {
    [UIAlertView bk_showAlertViewWithTitle:@"" message:NSLocalizedString(@"You mobile screen is captured.\n Please pay attention to password security.", nil) cancelButtonTitle:NSLocalizedString(@"Confirm",nil) otherButtonTitles:nil handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
